//
//  ConfirmViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/21.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class ConfirmViewController: BaseViewController {
    var dataSource:orderCheckOutItem?
    var receiverLabel:UILabel!
    var phoneLabel:UILabel!
    var addressLabel:UILabel!
    var scrollView:UIScrollView!
    var addressView:UIView!
    var identifyButton:UIButton!
    var cartTable:UITableView!
    let scrollHeight = windowHeight-64-49
    var cartDataSource:[cartListItem] = []
    var sendWayView:UIView!
    var payWayView:UIView!
    var payInvititleView:UIView!
    var moneyRestLabel:UILabel!
    var billContentField:UITextField!
    var cardPassword:UITextField!
    var otherField:UITextField!
     var selectButton:ImageHeadButton?
    var cardView:UIView!
    var otherView:UIView!
    var otherMoneyView:UIView!
    let baseHeight:CGFloat = 40.0
    let baseDistance:CGFloat = 5.0
    var switchBtn:UISwitch!
    var wkswitchBtn:UISwitch!
    var bottomView:UIView!
    var billBUttuon:UIButton!
    var moneyLabel:UILabel!
    var addressObj:AddressListItem?
    var dataNeedRefresh:Bool = false
    var lastPullData:Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "确认订单"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        // Do any additional setup after loading the view.
        view.backgroundColor = commonBackgoundColor
        scrollView = UIScrollView(frame: CGRectMake(0, 64, windowWidth, scrollHeight))
//        scrollView.scrollEnabled = false
//        scrollView.pagingEnabled = true
        scrollView.backgroundColor = commonBackgoundColor
        scrollView.delegate = self
        view.addSubview(scrollView)

    }
    func setupSubViews()->Void{
        self.setupBottomView()
        self.setupAddressView()
        self.setupIndentifyButton()
        self.createTableView()
        self.setupSendWayView()
        self.setupPayWayView()
        self.setupInvititleView()
        self.setupCardView()
        self.setupOtherView()
        self.setupOtherMoneyView()
        self.resetViewsFrame()
        dataNeedRefresh = true
    }
    func resetViewsFrame(){
        let height:CGFloat =  80.0*CGFloat(dataSource!.items!.count)
        if dataSource?.is_out_country == "0" && dataSource?.is_authentication == "-1"{
            identifyButton.frame = CGRectMake(0, CGRectGetMaxY(addressView.frame)+10, view.bounds.size.width, 40)
            cartTable.frame =  CGRectMake(0, CGRectGetMaxY(identifyButton.frame)+10, view.bounds.size.width, height)

        }
        else{
            identifyButton.frame = CGRectMake(0, CGRectGetMaxY(addressView.frame)+10, 0, 0)
            cartTable.frame =  CGRectMake(0, CGRectGetMaxY(identifyButton.frame), view.bounds.size.width, height)

        }
        sendWayView.frame = CGRectMake(0, CGRectGetMaxY(cartTable.frame)+10, view.bounds.size.width, 40)
         payWayView.frame = CGRectMake(0, CGRectGetMaxY(sendWayView.frame)+10, view.bounds.size.width, 40)
        payInvititleView.frame =  CGRectMake(0, CGRectGetMaxY(payWayView.frame), view.bounds.size.width, 110)
        cardView.frame =  CGRectMake(0, CGRectGetMaxY(payInvititleView.frame)+10, view.bounds.size.width, baseHeight*2)
        otherView.frame = CGRectMake(0, CGRectGetMaxY(cardView.frame)+10, view.bounds.size.width, baseHeight)
        otherMoneyView.frame = CGRectMake(0, CGRectGetMaxY(otherView.frame), otherMoneyView.bounds.size.width, otherMoneyView.bounds.size.height)
        scrollView.contentSize = CGSizeMake(view.bounds.size.width, CGRectGetMaxY(otherMoneyView.frame))
    }
    func queryCartDetails(sessionid:String!)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(sessionid, forKey: "sessionid")
        request.requestStart("/checkout/cartdetail", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                }
                catch let error as NSError {
                    print(error)
                }
                self.dataSource = (dic?.pareseDataToOrderCheckOutItem())!
                if let addressDic = self.dataSource?.address{
                    self.addressObj = addressDic.pareseDataToAddressItem()
                }
                dispatch_async(dispatch_get_main_queue()){
                    if self.lastPullData{
                        self.submitOrder()
                        return
                    }
                    if self.dataNeedRefresh{
                        self.resetOtherMoneyView()
                    }
                    else{
                        self.setupSubViews()

                    }
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                    self.showTips("加载失败")
                }
            }
        })
        dispatch_async(dispatch_get_main_queue()){
            if self.dataNeedRefresh{
                self.showProcess("正在处理...")

            }
            else{
                self.showProcess("加载中...")
            }
        }

    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if let sessionid = GlobalDataHelper.instance.session{
            self.queryCartDetails(sessionid)
        }
    }

    func showAddress(){
        let ctl = AddressManagerViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func setupAddressView()->Void{
        addressView = UIView(frame: CGRectMake(0, 5, view.bounds.size.width, 73))
        let btn = UIButton(frame: addressView.bounds)
        btn.addTarget(self, action: "showAddress", forControlEvents: UIControlEvents.TouchUpInside)
        addressView.addSubview(btn)
        addressView.backgroundColor = UIColor.whiteColor()
        //图片
        let imageview = UIImageView(frame: CGRectMake(5, (addressView.bounds.size.height-17)/2.0, 13, 17))
        imageview.image = UIImage(named: "location")
        addressView.addSubview(imageview)
        //收货人
        let receiver = UILabel(frame: CGRectMake(30,10, 150, 20))
        var name = ""
        if let user = self.dataSource?.address?["username"]{
            name = user as! String
        }
        receiver.text = "收货人：" + name
        receiver.font = UIFont.systemFontOfSize(14)
        receiverLabel = receiver
         addressView.addSubview(receiver)
        //电话
        let phone = UILabel(frame: CGRectMake(addressView.bounds.size.width-180, 10, 140, 20))
        phone.text = self.dataSource?.address?["telephone"] as? String
        phone.textAlignment = NSTextAlignment.Right
        phone.font = UIFont.systemFontOfSize(14)
        addressView.addSubview(phone)
        phoneLabel = phone
        //address
        let address = UILabel(frame: CGRectMake(30, 30, addressView.bounds.size.width-60, 40))
        address.text = self.dataSource?.address?["content"] as? String
        address.textAlignment = NSTextAlignment.Left
        address.font = UIFont.systemFontOfSize(12)
        address.numberOfLines = 0
        addressLabel = address
        addressView.addSubview(address)
        
        //图片
        let imageview2 = UIImageView(frame: CGRectMake(addressView.bounds.size.width-18, (addressView.bounds.size.height-11)/2.0, 6, 11))
        imageview2.image = UIImage(named: "forward_icon")
        addressView.addSubview(imageview2)
        
        scrollView.addSubview(addressView)
    }
    func setupIndentifyButton(){
        identifyButton = UIButton(frame: CGRectMake(0, CGRectGetMaxY(addressView.frame)+10, view.bounds.size.width, 40))
        identifyButton.backgroundColor = UIColor.whiteColor()
        identifyButton.clipsToBounds = true
        identifyButton.addTarget(self, action: "goIndentify", forControlEvents: UIControlEvents.TouchUpInside)
        let lbl1 = UILabel(frame: CGRectMake(10, 0,80,identifyButton.bounds.size.height))
        lbl1.text = "身份认证"
        lbl1.textColor = UIColor.darkGrayColor()
        lbl1.textAlignment = NSTextAlignment.Left
        lbl1.font = UIFont.systemFontOfSize(14)
        identifyButton.addSubview(lbl1)
        
        let lvButton = FRDLivelyButton(frame: CGRectMake(identifyButton.bounds.size.width-40, 10, 30, identifyButton.bounds.size.height-20))
        lvButton.options = [
            kFRDLivelyButtonColor: UIColor.lightGrayColor(),
            kFRDLivelyButtonHighlightedColor: UIColor.clearColor(),
            kFRDLivelyButtonHighlightAnimationDuration: (0.1),
            kFRDLivelyButtonHighlightScale: (0.9),
            kFRDLivelyButtonLineWidth: (1.0),
            kFRDLivelyButtonUnHighlightAnimationDuration: (0.15),
            kFRDLivelyButtonStyleChangeAnimationDuration: (0.3)
        ]
        lvButton.userInteractionEnabled = false;
        lvButton.setStyle(kFRDLivelyButtonStyleCaretRight, animated: false)
        identifyButton.addSubview(lvButton)
        scrollView.addSubview(identifyButton)
    }
    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        let height:CGFloat =  80.0*CGFloat(dataSource!.items!.count)
        cartTable = UITableView(frame: CGRectMake(0, CGRectGetMaxY(identifyButton.frame)+10, view.bounds.size.width, height), style: UITableViewStyle.Plain)
        cartTable.backgroundColor = UIColor.clearColor()
        cartTable.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
        cartTable.showsHorizontalScrollIndicator = false
        cartTable.showsVerticalScrollIndicator = false
        cartTable.dataSource = self
        cartTable.rowHeight = 80.0
        cartTable.delegate = self
        cartTable.scrollEnabled = false
        let nib = UINib(nibName:"OrderlistCell", bundle:nil)
        cartTable.registerNib(nib,forCellReuseIdentifier:"OrderlistCell")
        scrollView.addSubview(cartTable)
    }
    func setupSendWayView(){
        sendWayView = UIView(frame: CGRectMake(0, CGRectGetMaxY(cartTable.frame)+10, view.bounds.size.width, 40))
        sendWayView.backgroundColor = UIColor.whiteColor()
        let lbl1 = UILabel(frame: CGRectMake(10, 0,80,sendWayView.bounds.size.height))
        lbl1.text = "配送方式"
        lbl1.textColor = UIColor.darkGrayColor()
        lbl1.textAlignment = NSTextAlignment.Left
        lbl1.font = UIFont.systemFontOfSize(14)
        sendWayView.addSubview(lbl1)
        
        let lbl2 = UILabel(frame: CGRectMake(sendWayView.bounds.size.width-110, 0,100, sendWayView.bounds.size.height))
        lbl2.text = "标准快递"
//                lbl2.textColor = commonRedColor
        lbl2.textAlignment = NSTextAlignment.Right
        lbl2.font = UIFont.systemFontOfSize(14)
        sendWayView.addSubview(lbl2)
        scrollView.addSubview(sendWayView)
    }
    func setupPayWayView(){
        payWayView = UIView(frame: CGRectMake(0, CGRectGetMaxY(sendWayView.frame)+10, view.bounds.size.width, 40))
        payWayView.backgroundColor = UIColor.whiteColor()
        let lbl1 = UILabel(frame: CGRectMake(10, 0,80,payWayView.bounds.size.height))
        lbl1.text = "支付方式"
        lbl1.textColor = UIColor.darkGrayColor()
        lbl1.textAlignment = NSTextAlignment.Left
        lbl1.font = UIFont.systemFontOfSize(14)
        payWayView.addSubview(lbl1)
        
        let lbl2 = UILabel(frame: CGRectMake(payWayView.bounds.size.width-110, 0,100, payWayView.bounds.size.height))
        lbl2.text = "在线支付"
        //                lbl2.textColor = commonRedColor
        lbl2.textAlignment = NSTextAlignment.Right
        lbl2.font = UIFont.systemFontOfSize(14)
        payWayView.addSubview(lbl2)
        scrollView.addSubview(payWayView)

    }
    func setupInvititleView(){

        payInvititleView = UIView(frame: CGRectMake(0, CGRectGetMaxY(payWayView.frame), view.bounds.size.width, 110))
        payInvititleView.backgroundColor = UIColor.whiteColor()
        let sepView = UIView(frame: CGRectMake(0,0, payInvititleView.bounds.size.width, onePix))
        sepView.backgroundColor = view.backgroundColor
        payInvititleView.addSubview(sepView)
        
        let lbl1 = UILabel(frame: CGRectMake(10, 10,80,20))
        lbl1.text = "发票信息"
        lbl1.textColor = UIColor.darkGrayColor()
        lbl1.textAlignment = NSTextAlignment.Left
        lbl1.font = UIFont.systemFontOfSize(14)
        payInvititleView.addSubview(lbl1)
        
        //选择按钮
        var menuButton:ImageHeadButton?
        let width:CGFloat = 110
        let height:CGFloat = 30
        let titleArray:[String] = ["无需发票","个人","公司"]
        for i in 0...2{
            menuButton = ImageHeadButton(frame: CGRectMake(width*CGFloat(i)+10, CGRectGetMaxY(lbl1.frame), width-20, height))
            menuButton?.imageSize = CGSizeMake(12, 11)
            menuButton?.backgroundColor = UIColor.clearColor()
            menuButton?.setTitle(titleArray[i], forState: UIControlState.Normal)
            menuButton?.setImage(UIImage(named: "nor_order_radio"), forState: UIControlState.Normal)
            menuButton?.setImage(UIImage(named: "downr_order_radio"), forState: UIControlState.Selected)
//            menuButton?.setTitleColor(commonRedColor, forState: UIControlState.Selected)
            menuButton?.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            menuButton?.titleLabel?.font = UIFont.systemFontOfSize(14)
            menuButton?.titleLabel?.textAlignment = NSTextAlignment.Left
            menuButton?.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            payInvititleView.addSubview(menuButton!)
            menuButton?.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
            if i == 0{
                self.buttonClick(menuButton!)
            }
        }
        
        billContentField = UITextField(frame: CGRectMake(25, payInvititleView.bounds.size.height-40, payInvititleView.bounds.size.width-50, 30))
        billContentField.borderStyle = UITextBorderStyle.RoundedRect
        billContentField.backgroundColor = commonBackgoundColor
        billContentField.placeholder = "请输入发票抬头"
        billContentField.font = UIFont.systemFontOfSize(14)
        payInvititleView.addSubview(billContentField)
        scrollView.addSubview(payInvititleView)
    }
    func setupCardView(){
        cardView = LineView(frame: CGRectMake(0, CGRectGetMaxY(payInvititleView.frame)+10, view.bounds.size.width, baseHeight*2))
        cardView.clipsToBounds = true
        let line1 = LineView(frame: CGRectMake(0, 0, view.bounds.size.width, baseHeight))
        let label = UILabel(frame: CGRectMake(15, 0, 50, baseHeight))
        label.font = UIFont.systemFontOfSize(14)
        label.text = "旺 卡"
        line1.addSubview(label)
        
        cardPassword = UITextField(frame: CGRectMake(70, 0, payInvititleView.bounds.size.width-80, baseHeight))
        cardPassword.borderStyle = UITextBorderStyle.None
        cardPassword.placeholder = "请输入旺卡密码"
        cardPassword.font = UIFont.systemFontOfSize(14)
        line1.addSubview(cardPassword)
        cardView.addSubview(line1)
        
        wkswitchBtn = UISwitch(frame: CGRectMake(view.bounds.size.width-51-20, 5, 51, 31))
        wkswitchBtn.setOn(false, animated: false)
        wkswitchBtn.tintColor = commonRedColor
        wkswitchBtn.onTintColor = commonRedColor
        wkswitchBtn.addTarget(self, action: "wkvalueDidChanged:", forControlEvents: UIControlEvents.ValueChanged)
        line1.addSubview(wkswitchBtn)
        
        let line2 = LineView(frame: CGRectMake(0, baseHeight, view.bounds.size.width, baseHeight))
        let label2 = UILabel(frame: CGRectMake(15, 0, 50, baseHeight))
        label2.font = UIFont.systemFontOfSize(14)
        label2.text = "余 额"
        line2.addSubview(label2)
        
        moneyRestLabel = UILabel(frame: CGRectMake(70, 0, 150, baseHeight))
        moneyRestLabel.font = UIFont.systemFontOfSize(14)
        moneyRestLabel.text =  self.dataSource?.balance
        line2.addSubview(moneyRestLabel)
        
        
        switchBtn = UISwitch(frame: CGRectMake(view.bounds.size.width-51-20, 5, 51, 31))
        switchBtn.setOn(false, animated: false)
        switchBtn.tintColor = commonRedColor
        switchBtn.onTintColor = commonRedColor
        switchBtn.addTarget(self, action: "valueDidChanged:", forControlEvents: UIControlEvents.ValueChanged)
        line2.addSubview(switchBtn)
        
        cardView.addSubview(line2)

        scrollView.addSubview(cardView)


    }
    func setupOtherView()->Void{
        otherView = LineView(frame: CGRectMake(0, CGRectGetMaxY(cardView.frame)+10, view.bounds.size.width, baseHeight))
        otherView.clipsToBounds = true
        let line1 = LineView(frame: CGRectMake(0, 0, view.bounds.size.width, baseHeight))
        let label = UILabel(frame: CGRectMake(15, 0, 50, baseHeight))
        label.font = UIFont.systemFontOfSize(14)
        label.text = "备 注"
        line1.addSubview(label)
        
        otherField = UITextField(frame: CGRectMake(70, 0, payInvititleView.bounds.size.width-80, baseHeight))
        otherField.borderStyle = UITextBorderStyle.None
        otherField.placeholder = "请输入订单备注"
        otherField.font = UIFont.systemFontOfSize(14)
        line1.addSubview(otherField)
        otherView.addSubview(line1)
        scrollView.addSubview(otherView)
    }
    func setupOtherMoneyView()->Void{
        otherMoneyView = LineView()
        var count:NSInteger = 0
        if let array = self.dataSource?.totals{
            count = array.count
            otherMoneyView.frame = CGRectMake(0, CGRectGetMaxY(otherView.frame)+10, view.bounds.size.width, CGFloat(count)*30.0)
            otherMoneyView.clipsToBounds = true
            let hieght:CGFloat = 22.0
            let distance:CGFloat = 5
            for i in 0..<count{
                let dic = array[i]
                let labl1 = UILabel(frame: CGRectMake(10, (distance+hieght)*CGFloat(i)+8, 100, hieght))
                labl1.textColor = UIColor.darkGrayColor()
                labl1.font = UIFont.boldSystemFontOfSize(14)
                labl1.text = dic["title"] as? String
                labl1.textAlignment = NSTextAlignment.Left
                otherMoneyView.addSubview(labl1)
                
                let labl2 = UILabel(frame: CGRectMake(otherMoneyView.bounds.size.width-110, (distance+hieght)*CGFloat(i)+8, 100, hieght))
                labl2.textColor = UIColor.darkGrayColor()
                labl2.font = UIFont.boldSystemFontOfSize(14)
                labl2.text = dic["value"] as? String
                labl2.textAlignment = NSTextAlignment.Right
                otherMoneyView.addSubview(labl2)
            }

        }
//        //商品金额
//        let labl1 = UILabel(frame: CGRectMake(10, 8, 100, hieght))
//        labl1.textColor = UIColor.darkGrayColor()
//        labl1.font = UIFont.boldSystemFontOfSize(14)
//        labl1.text = "实付金额"
//        labl1.textAlignment = NSTextAlignment.Left
//        otherMoneyView.addSubview(labl1)
//        
//        let labl2 = UILabel(frame: CGRectMake(otherMoneyView.bounds.size.width-110, 8, 100, hieght))
//        labl2.textColor = UIColor.darkGrayColor()
//        labl2.font = UIFont.boldSystemFontOfSize(14)
//        labl2.text = "¥123.0"
//        labl2.textAlignment = NSTextAlignment.Right
//        otherMoneyView.addSubview(labl2)
//        
//        //行邮税
//        let labl3 = UILabel(frame: CGRectMake(10, CGRectGetMaxY(labl1.frame)+distance, 100, hieght))
//        labl3.textColor = UIColor.darkGrayColor()
//        labl3.font = UIFont.boldSystemFontOfSize(14)
//        labl3.text = "行邮税"
//        labl3.textAlignment = NSTextAlignment.Left
//        otherMoneyView.addSubview(labl3)
//        
//        let labl4 = UILabel(frame: CGRectMake(CGRectGetMinX(labl2.frame), CGRectGetMaxY(labl1.frame)+distance, 100, hieght))
//        labl4.textColor = UIColor.darkGrayColor()
//        labl4.font = UIFont.boldSystemFontOfSize(14)
//        labl4.text = "＋¥12.0"
//        labl4.textAlignment = NSTextAlignment.Right
//        otherMoneyView.addSubview(labl4)
//        
//        //运费
//        let labl5 = UILabel(frame: CGRectMake(10, CGRectGetMaxY(labl3.frame)+distance, 100, hieght))
//        labl5.textColor = UIColor.darkGrayColor()
//        labl5.font = UIFont.boldSystemFontOfSize(14)
//        labl5.text = "运费"
//        labl5.textAlignment = NSTextAlignment.Left
//        otherMoneyView.addSubview(labl5)
//        
//        let labl6 = UILabel(frame: CGRectMake(CGRectGetMinX(labl2.frame), CGRectGetMaxY(labl3.frame)+distance, 100, hieght))
//        labl6.textColor = UIColor.darkGrayColor()
//        labl6.font = UIFont.boldSystemFontOfSize(14)
//        labl6.text = "＋¥10.0"
//        labl6.textAlignment = NSTextAlignment.Right
//        otherMoneyView.addSubview(labl6)
//        
//        //余额
//        let labl7 = UILabel(frame: CGRectMake(10, CGRectGetMaxY(labl5.frame)+distance, 100, hieght))
//        labl7.textColor = UIColor.darkGrayColor()
//        labl7.font = UIFont.boldSystemFontOfSize(14)
//        labl7.text = "余额"
//        labl7.textAlignment = NSTextAlignment.Left
//        otherMoneyView.addSubview(labl7)
//        
//        let labl8 = UILabel(frame: CGRectMake(CGRectGetMinX(labl2.frame), CGRectGetMaxY(labl5.frame)+distance, 100, hieght))
//        labl8.textColor = UIColor.darkGrayColor()
//        labl8.font = UIFont.boldSystemFontOfSize(14)
//        labl8.text = "－¥100.0"
//        labl8.textAlignment = NSTextAlignment.Right
//        otherMoneyView.addSubview(labl8)
        
        scrollView.addSubview(otherMoneyView)
    }
    func buttonClick(button:UIButton){
        if button == selectButton{
            return
        }
        button.selected = true
        selectButton?.selected = false
        selectButton = button as? ImageHeadButton
    }
    func setupBottomView(){
        bottomView = UIView(frame: CGRectMake(0, view.bounds.size.height-49, view.bounds.size.width, 49))
        view.addSubview(bottomView)
        //背景
        let line = UIImageView(frame: CGRectMake(0, 0, bottomView.bounds.size.width, onePix))
        line.backgroundColor = commonRedColor
        bottomView.addSubview(line)

        //总金额
        let allLabel = UILabel(frame: CGRectMake(10, 0, 100, bottomView.bounds.size.height))
        allLabel.textColor = UIColor.darkGrayColor()
        allLabel.font = UIFont.boldSystemFontOfSize(14)
        allLabel.text = "实付金额"
        allLabel.textAlignment = NSTextAlignment.Center
        bottomView.addSubview(allLabel)
        moneyLabel = UILabel(frame: CGRectMake(CGRectGetMaxX(allLabel.frame)+5, 0, 120, bottomView.bounds.size.height))
        moneyLabel.textColor = commonRedColor
        moneyLabel.font = UIFont.boldSystemFontOfSize(14)
        moneyLabel.text = "¥"+self.dataSource!.total!
        bottomView.addSubview(moneyLabel)
        //提交订单
        billBUttuon = UIButton(frame: CGRectMake(CGRectGetMaxX(moneyLabel.frame),0, bottomView.bounds.size.width - CGRectGetMaxX(moneyLabel.frame), bottomView.bounds.size.height))
        billBUttuon.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        billBUttuon.setTitle("提交订单", forState: UIControlState.Normal)
        billBUttuon.backgroundColor = commonRedColor
        billBUttuon.addTarget(self, action: "billBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        bottomView.addSubview(billBUttuon)
        view.addSubview(bottomView)
    }
    func resetOtherMoneyView(){
        var name = ""
        if let user = self.dataSource?.address?["username"]{
            name = user as! String
        }
        receiverLabel.text = "收货人：" + name
        phoneLabel.text = self.dataSource?.address?["telephone"] as? String
        addressLabel.text = self.dataSource?.address?["content"] as? String
        for oneview in self.otherMoneyView.subviews {
            oneview.removeFromSuperview()
        }
        var count:NSInteger = 0
        if let array = self.dataSource?.totals{
            count = array.count
            otherMoneyView.frame = CGRectMake(0, CGRectGetMaxY(otherView.frame)+10, view.bounds.size.width, CGFloat(count)*30.0)
            otherMoneyView.clipsToBounds = true
            let hieght:CGFloat = 22.0
            let distance:CGFloat = 5
            for i in 0..<count{
                let dic = array[i]
                let labl1 = UILabel(frame: CGRectMake(10, (distance+hieght)*CGFloat(i)+8, 100, hieght))
                labl1.textColor = UIColor.darkGrayColor()
                labl1.font = UIFont.boldSystemFontOfSize(14)
                labl1.text = dic["title"] as? String
                labl1.textAlignment = NSTextAlignment.Left
                otherMoneyView.addSubview(labl1)
                
                let labl2 = UILabel(frame: CGRectMake(otherMoneyView.bounds.size.width-110, (distance+hieght)*CGFloat(i)+8, 100, hieght))
                labl2.textColor = UIColor.darkGrayColor()
                labl2.font = UIFont.boldSystemFontOfSize(14)
                labl2.text = dic["value"] as? String
                labl2.textAlignment = NSTextAlignment.Right
                otherMoneyView.addSubview(labl2)
            }
        }
        moneyLabel.text = self.dataSource?.total
        self.resetViewsFrame()
    }
    func goIndentify(){
        let ctl = IdentifyViewController()
        self.navigationController?.pushViewController(ctl, animated: true)
    }
    func valueDidChanged(sender:UISwitch)->Void{
       if  moneyRestLabel.text == "0"{
            self.showTips("余额不足")
            return
        }
        if sender.on{
            self.useRestCard(true)
        }
        else{
            self.useRestCard(false)
        }
    }
    func wkvalueDidChanged(sender:UISwitch)->Void{
        if let name = self.cardPassword.text{
            let nameinfo = name.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) as NSString
            if nameinfo.length == 0{
                self.showTips("旺卡号码不能为空")
                return
            }
        }
        else{
            self.showTips("旺卡号码不能为空")
            return
        }
        if sender.on{
            self.useWangCard(true)
        }
        else{
            self.useWangCard(false)
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    func useWangCard(use:Bool)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        print(self.self.cardPassword.text!)
        parameters.setObject(self.cardPassword.text!, forKey: "giftcardCode")
        if use{
            parameters.setObject("0", forKey: "removeGiftcard")
        }
        else{
            parameters.setObject("1", forKey: "removeGiftcard")
        }
        request.requestStart("/checkout/saveGiftcard", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                }
                if (dic?["result"])! as! String == "0"{
                    if let sessionid = GlobalDataHelper.instance.session{
                        self.queryCartDetails(sessionid)
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
//                        self?.cardPassword.text = nil
                        })
                    
                }
            }
        })
    }
    func useRestCard(use:Bool)->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        print(self.self.cardPassword.text!)
        if use{
            parameters.setObject("1", forKey: "use_customer_balance")
        }
        else{
            parameters.setObject("0", forKey: "use_customer_balance")
        }
        request.requestStart("/checkout/appsavePaymentData", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                        return
                    }
                }
                if (dic?["result"])! as! String == "0"{
                    if let sessionid = GlobalDataHelper.instance.session{
                        self.queryCartDetails(sessionid)
                    }
                }
                else{
                    dispatch_async(dispatch_get_main_queue(), {[weak self] in
                        self?.showTips(dic?["msg"] as? String)
                        //                        self?.cardPassword.text = nil
                        })
                    
                }
            }
        })
    }
    @IBAction func billBtnClick(button:UIButton){
        if dataSource?.is_out_country == "0" && dataSource?.is_authentication == "-1"{
            self.showTips("该订单需要实名认证，请先进行实名认证")
            return
        }
        if let sessionid = GlobalDataHelper.instance.session{
            self.queryCartDetails(sessionid)
        }
        self.lastPullData = true

    }
    func submitOrder()->Void{
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
        //        var name = ""
        //        if let user = self.dataSource?.address?["username"]{
        //            name = user as! String
        //        }
        
        if self.addressObj == nil{
            self.showTips("地址信息有误")
            return
        }
        parameters.setObject(self.addressObj!.username!, forKey: "cn_name")
        
        parameters.setObject(self.addressObj!.cn_province!, forKey: "cn_province")
        parameters.setObject(self.addressObj!.cn_city!, forKey: "cn_city")
        parameters.setObject(self.addressObj!.cn_district!, forKey: "cn_district")
        parameters.setObject(self.addressObj!.content!, forKey: "street")
        parameters.setObject(self.addressObj!.postCode!, forKey: "postcode")
        parameters.setObject(self.addressObj!.telephone!, forKey: "telephone")
        parameters.setObject("CN", forKey: "country_id")
        request.requestStart("/checkout/submitOrder", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){

                        let str = dic?["data"]?["order_status"] as? String
                        if let info = str{
                            if info == "paid"{
                                self.showTips("支付成功"){
                                    self.navigationController?.popViewControllerAnimated(true)
                                }
                            }
                            else{
                                let ctl = PayViewController()
                                ctl.orderId = dic?["data"]?["order_id"] as? String
                                ctl.payUrl = dic?["data"]?["payUrl"] as? String
                                ctl.total = self.dataSource?.total
                                self.navigationController?.pushViewController(ctl, animated: true)
                            }
                        }
                        
                    }
                }
                //                self.tableDataSource = (dic?.pareseDataToCartListArray())!
                //                self.totalMoney = dic?["data"]?["base_total"] as? String
                //                dispatch_async(dispatch_get_main_queue()){
                //                    self.cartTable.reloadData()
                //                    self.moneyLabel.text = self.totalMoney
                //                }
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                    self.showTips("订单提交失败")
                }
            }
        })
        dispatch_async(dispatch_get_main_queue()){
            self.showProcess("正在提交...")
        }

    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension ConfirmViewController:UITableViewDataSource,UITableViewDelegate{
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return self.dataSource!.items!.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("OrderlistCell", forIndexPath: indexPath) as! OrderlistCell
        let obj  = dataSource!.items![indexPath.row]
        cell.wineImageView.setImageWithUrl(obj.image!, defaultImage:nil)
        cell.wineTitle.text = obj.name
        cell.wineNumber.text = "X "+obj.qty!
        cell.totalMoney.text = obj.price
        cell.otherInfo.hidden = true
        cell.setTopConstraintConst(0.0)
//        cell.otherInfo.text = "参数："+obj.weight!
        return cell
    }
    func scrollViewDidScroll(scrollView: UIScrollView){
         billContentField.resignFirstResponder()
        cardPassword.resignFirstResponder()
        otherField.resignFirstResponder()
    }
}
